#include "threadpool.h"

int exitpipe[2];
void hanlder(int signum){

    printf("signum = %d\n", signum);
    write(exitpipe[1],"1",1);
}
int main(int argc ,char* argv[]){
    ARGS_CHECK(argc,4);
    pipe(exitpipe);
    if(fork()){
        close(exitpipe[0]);
        signal(SIGUSR1,hanlder);
        wait(NULL);
        printf("父进程收到信息要退出\n");
        exit(0);
    }
    threadpool_t *threadpool = NULL;
    int workNum=atoi(argv[3]);
    threadpoolInit(threadpool,workNum);

    int sockfd=tcpinit(argv[1],argv[2]);

    int epfd=epoll_create(1);
    
    epolladd(epfd,sockfd);
    
    close(exitpipe[1]);
    epolladd(epfd,exitpipe[0]);

    struct epoll_event readySet[1024]={0};

    while(1){
        int readyNum=epoll_wait(epfd, readySet, 1024, -1);
        for(int i=0;i<readyNum;i++){
            if(readySet[i].data.fd==sockfd){
                int netfd=accept(sockfd,NULL,NULL);
                printf("新连接已经入 netfd=%d\n",netfd);
                pthread_mutex_lock(&threadpool->mutex);
                Quepush(threadpool->taskArr,netfd);
                pthread_cond_broadcast(&threadpool->cond);
                pthread_mutex_unlock(&threadpool->mutex);
            }else{
                puts("工人线程将要关闭");
                pthread_mutex_lock(&threadpool->mutex);
                threadpool->exitflag=1;
                pthread_cond_broadcast(&threadpool->cond);
                pthread_mutex_unlock(&threadpool->mutex);
                for(int j=0;j<workNum;j++){
                    pthread_join(threadpool->tidArr->arr[j],NULL);
                }
                exit(0);
            }
        }
    }

}